import Foundation

//节点
public class Node: CustomStringConvertible {
    public var value: Int
    public var next: Node?
    
    public init(_ value: Int) {
        self.value = value
        next = nil
    }
    
    public var description: String {
        return "\(value)"
    }
}


//链表
public class NodeList: CustomStringConvertible {
    public var head: Node?
    public var tail: Node?
    
    public init() { }
    
    //尾插法
    public func appendToTail(_ value: Int) -> Self {
        if self.tail != nil {
            self.tail?.next = Node(value)
            self.tail = self.tail?.next
        }else{
            self.tail = Node(value)
            self.head = self.tail
        }
        return self
    }
    
    //头插法
    public func appendToHead(_ value: Int) -> Self {
        let node = Node(value)
        if self.head != nil {
            node.next = self.head
            self.head = node
        }else{
            self.head = node
            self.tail = node
        }
        return self
    }
    
    
    // 尾插法
    public func appendNodeToTail(_ node: Node) -> Self {
        if self.tail != nil {
            self.tail?.next = node
            self.tail = node
        } else {
            self.head = node
            self.tail = node
        }
        return self
    }
    
    // 头插法
    public func appendNodeToHead(_ node: Node) -> Self {
        if self.head != nil {
            let head = self.head
            node.next = head
            self.head = node
        } else {
            self.head = node
            self.tail = node
        }
        return self
    }

    
    public func nodeAt(_ index: Int) -> Node? {
        if index >= 0 {
            var i = 0
            var node = self.head
            while i != index {
                node = node?.next
                i += 1
            }
            return node
        }
        return nil
    }
    
    public var description: String {
        var text = "["
        var node = head
        while node != nil {
            text += "\(node!.value)"
            node = node!.next
            if node != nil {
                text += ", "
            }
        }
        return text + "]"
    }
}
